package utils

import (
	"bufio"
	"fmt"
	"os"
)

type FileCache struct {
	buff     *bufio.Reader
	fp       *os.File
	fileName string
}

func NewFileCache(fileName string) (*FileCache, error) {
	if fileInfo, err := os.Stat(fileName); err != nil {
		return nil, err
	} else if !fileInfo.Mode().IsRegular() {
		return nil, fmt.Errorf("%s is not a file", fileName)
	}

	if fp, err := os.Open(fileName); err != nil {
		return nil, err
	} else {
		return &FileCache{fileName: fileName, fp: fp, buff: bufio.NewReader(fp)}, nil
	}
}

func (f FileCache) ReadLine() (string, error) {
	for {
		line, prefix, err := f.buff.ReadLine()
		if err != nil {
			return "", err
		}
		if prefix {
			continue
		}
		return string(line), nil
	}
}

func (f FileCache) Close() {
	if f.fp != nil {
		_ = f.fp.Close()
	}
}
